package com.shop.mall.servlet;

import com.alibaba.fastjson.JSONObject;
import com.shop.mall.dao.impl.UserDaoImpl;
import com.shop.mall.entity.User;
import com.shop.mall.utils.BaseResultVO;
import com.shop.mall.utils.GetUUIDUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author admin
 * @version 1.0
 * @date 2019/4/24
 */
@WebServlet(urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = -8549693792110472069L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行LoginServlet doPost()");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String operation = request.getParameter("operation");
        if (operation != null) {
            switch (operation) {
                case "userInfo":
                    userInfo(request, response);
                    break;
                case "login":
                    login(request, response);
                    break;
                case "registerUser":
                    registerUser(request, response);
                    break;
                case "updateUser":
                    updateUser(request, response);
                    break;
                case "deleteUser":
                    deleteUser(request, response);
                    break;
                case "webLogin":
                    webLogin(request, response);
                    break;
                default:
                    break;
            }
        }
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>User Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();

    }

    private void userInfo(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        UserDaoImpl userDao = new UserDaoImpl();
        try {
            userDao.select(Integer.parseInt(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setAttribute("name", "托尼斯达克");
        //判断输入的用户名和密码是不是都为admin
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        PrintWriter out = response.getWriter();
        JSONObject object = new JSONObject(true);
        BaseResultVO resultVO = new BaseResultVO();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            object.put("username", username);
            object.put("password", password);
            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(object));
            resultVO.setMessage("请填写用户名和密码!");
            out.println(resultVO);
            out.close();
            out.flush();
        }
        UserDaoImpl udao = new UserDaoImpl();
        try {
            Boolean flag = udao.login(username.trim(), password.trim());
            if (flag) {
                //请求重定向
                response.sendRedirect(request.getContextPath() + "/pages/book/success.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }

//        if ("admin".equals(username) && "123456".equals(password)) {
//            req.getSession().setAttribute("username", username);
//
//            PrintWriter out = resp.getWriter();
//            out.println("<h1>" + username + "</h1>");
//            //req.getContextPath()去到的是webRoot目录
//            System.out.println("ContextPath():"+req.getContextPath() + "/pages/book/success.jsp");
//            //请求重定向
//            resp.sendRedirect(req.getContextPath() + "/pages/book/success.jsp");
//            //关闭输入流
//            out.close();
//            //清空缓冲区
//            out.flush();
//            return;
//        } else {
//            resp.sendRedirect(req.getContextPath() + "/pages/book/fail.jsp");
//            return;
//        }
    }
    private void webLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        PrintWriter out = response.getWriter();
        JSONObject object = new JSONObject(true);
        BaseResultVO resultVO = new BaseResultVO();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            object.put("username", username);
            object.put("password", password);
            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(object));
            resultVO.setMessage("请填写用户名和密码!");
            out.println(resultVO);
            out.close();
            out.flush();
        }
        UserDaoImpl udao = new UserDaoImpl();
        try {
            Boolean flag = udao.webLogin(username.trim(), password.trim());
            if (flag) {
                resultVO.setResult(true);
                resultVO.setCode(0);
                object.put("username",username);
                object.put("password",password);
                resultVO.setData(object.toJSONString());
                System.out.println("操作成功," + resultVO);
                response.sendRedirect(request.getContextPath() + "/pages/book/index.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void registerUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String tel = request.getParameter("tel");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        String role = request.getParameter("role");
        String status = request.getParameter("status");

        PrintWriter out = response.getWriter();
        JSONObject object = new JSONObject(true);
        BaseResultVO resultVO = new BaseResultVO();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            object.put("id", GetUUIDUtil.getId());
            object.put("username", username);
            object.put("password", password);
            object.put("tel", tel);
            object.put("email", email);
            object.put("sex", sex);
            object.put("role", role);
            object.put("status", status);

            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(object));
            resultVO.setMessage("请填写用户完整信息后在尝试提交");
            out.println(resultVO);
            out.close();
            out.flush();
        }
        UserDaoImpl udao = new UserDaoImpl();
        User user = new User();
        user.setId(Long.valueOf(GetUUIDUtil.getId()));
        user.setName(username);
        user.setPassword(password);
        user.setTel(tel);
        user.setEmail(email);
        user.setSex(sex);
        user.setRole(role);
        user.setStatus(status);
        try {
            int flag = udao.regist(user);
            if (flag > 0) {
                resultVO.setResult(true);
                resultVO.setCode(0);
                resultVO.setData(JSONObject.toJSONString(user));
                System.out.println("操作成功," + resultVO);
                //请求重定向
                response.sendRedirect(request.getContextPath() + "/pages/book/login.jsp");
                return;
            }
            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(user));
            System.out.println("操作失败," + resultVO);
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.registerUser(request, response);
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            PrintWriter out = response.getWriter();
            out.println("要删除的id:" + id);
            out.println("<br/>请选择要删除的选项");
            out.close();
            out.flush();
        }
        UserDaoImpl udao = new UserDaoImpl();
        try {
            int flag = udao.delete(Integer.parseInt(id));
            if (flag > 0) {
                //请求重定向
                response.sendRedirect(request.getContextPath() + "/pages/book/success.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
